//
//  JMFeedbackController.m
//  PicChouse
//
//  Created by 赵俊明 on 2019/1/22.
//  Copyright © 2019 JunMing. All rights reserved.
//

#import "JMFeedbackController.h"
#import "NetWorkSession.h"

typedef void(^uploadStatus)(BOOL success, id  _Nullable responseObject, NSString * _Nullable url);

@interface JMFeedbackController ()<UITextViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (nonatomic, strong) JMFeedbackTextView * textView;
@property (nonatomic, strong) UILabel *numLabel;
@property (nonatomic, strong) UILabel *iLabel;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIView *tfView;

@property(nonatomic,strong) UICollectionView *CollectionView;
@property(nonatomic,assign) CGFloat collectionFrameY;
@property(nonatomic,strong) NSMutableArray *dataSource;
@end
@implementation JMFeedbackController {
    NSString *contentStr;
    NSString *phoneStr;
}

static NSString * const reuseIdentifier = @"LQPhotoViewCell";
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"帮助与反馈";
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightBarButtonItem:)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    [self initViews];
}

#pragma mark - **************** 上传反馈数据
// 循环上传，保证上传队列完成后写入数据库
- (void)clickRightBarButtonItem:(id)sender {
    
    JMFeedbackModel *model = self.dataSource.firstObject;
    NSString *data = [NSString stringWithFormat:@"%@<$>%@<$>%@",model.filePath,contentStr,phoneStr];
    NSData *imageData = [self compressImage:model.image toByte:153600];
    if (imageData) {
        NSDictionary *params = @{@"path":@"/var/www/html/source/wallpaper_upload/",@"uname":@"MasterBoard"};
        [NetWorkSession upload:@"file" filename:model.filePath.lastPathComponent mimeType:@"image/png" data:imageData parmas:params status:^(BOOL success, id  _Nullable responseObject, NSString * _Nullable url) {
            [NetWorkSession feedback:data sratus:^(NSDictionary * _Nonnull info) {
                NSLog(@"info:%@",info);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }];
        }];
    }else {
        [NetWorkSession feedback:data sratus:^(NSDictionary * _Nonnull info) {
            NSLog(@"info:%@",info);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }];
    }
    [_textView resignFirstResponder];
    [self.view endEditing:YES];
    NSLog(@"------点击了提交");
}

- (void)initViews {
    CGFloat s_width = [UIScreen mainScreen].bounds.size.width;
    UILabel *qLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, s_width - 30, 30)];
    qLabel.text = @"问题和意见";
    // [UIColor colorWithHexString:@"555555"];
    qLabel.textColor = [UIColor grayColor];
    qLabel.font = [UIFont systemFontOfSize:16];
    qLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:qLabel];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(-0.5, qLabel.frame.origin.y + qLabel.frame.size.height + 5, s_width+1, 165)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.borderWidth = 0.1;
    view.layer.cornerRadius = 2;
    view.layer.masksToBounds = YES;
    [self.view addSubview:view];
    
    _textView = [[JMFeedbackTextView alloc]initWithFrame:CGRectMake(0, 0, s_width, 140)];
    _textView.backgroundColor = [UIColor whiteColor];
    _textView.delegate = self;
    _textView.font = [UIFont systemFontOfSize:15.f];
    _textView.textColor = [UIColor blackColor];
    _textView.textAlignment = NSTextAlignmentLeft;
    // JMColor(0x89, 0x89, 0x89);
    _textView.placeholderColor = [UIColor grayColor];
    _textView.placeholder = @"请输入不小于10个字的描述~";
    [view addSubview:_textView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEditChanged:) name:UITextViewTextDidChangeNotification object:_textView];
    
    _numLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, _textView.frame.origin.y + _textView.frame.size.height, s_width - 30, 20)];
    _numLabel.font = [UIFont systemFontOfSize:14.f];
    _numLabel.textColor = [UIColor lightGrayColor];
    _numLabel.text = @"0/150";
    _numLabel.backgroundColor = [UIColor whiteColor];
    _numLabel.textAlignment = NSTextAlignmentRight;
    [view addSubview:_numLabel];
    
    
    _iLabel = [[UILabel alloc]initWithFrame:CGRectMake(qLabel.frame.origin.x, view.frame.origin.y + view.frame.size.height + 10, qLabel.frame.size.width, qLabel.frame.size.height)];
    _iLabel.text = @"请提供相关问题的截图或照片(0/3)";
    // [UIColor colorWithHexString:@"555555"];
    _iLabel.textColor = [UIColor grayColor];
    _iLabel.font = [UIFont systemFontOfSize:16];
    _iLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_iLabel];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _iLabel.frame.origin.y + _iLabel.frame.size.height + 10, s_width, (s_width - 50) / 4 + 20)];
    [self.view addSubview:_scrollView];
    _dataSource = [NSMutableArray array];
    JMFeedbackModel *model = [[JMFeedbackModel alloc] init];
    model.image = [UIImage imageNamed:@"pick_plus"];
    [_dataSource addObject:model];
    
    _tfView = [[UIView alloc]initWithFrame:CGRectMake(1, _scrollView.frame.origin.y + _scrollView.frame.size.height + 10, s_width - 2, 44)];
    _tfView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_tfView];
    
    _textField = [[UITextField alloc]initWithFrame:CGRectMake(15, 0, s_width - 30, 44)];
    _textField.placeholder = @"联系方式";
    _textField.font = [UIFont systemFontOfSize:15];
    _textField.backgroundColor = [UIColor whiteColor];
    // [UIColor colorWithHexString:@"555555"];
    _textField.textColor = [UIColor grayColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldEditChanged:) name:UITextFieldTextDidChangeNotification object:_textField];
    [_tfView addSubview:_textField];
    
    [self LQPhotoPicker_initPickerView];
}

- (void)textViewEditChanged:(NSNotification *)obj {
    UITextView *tv = (UITextView *)obj.object;
    if (tv.text.length > 150) { tv.text = [tv.text substringToIndex:150]; }
    contentStr = tv.text;
    _numLabel.text = [NSString stringWithFormat:@"%lu/150", (unsigned long)tv.text.length];
    [self rightItemEnable];
}

- (void)textFieldEditChanged:(NSNotification *)obj {
    UITextField *tf = (UITextField *)obj.object;
    if (tf.text.length > 11) {tf.text = [tf.text substringToIndex:11];}
    phoneStr = tf.text;
    [self rightItemEnable];
}

- (void)rightItemEnable {
    if (_dataSource.count > 1 || contentStr.length > 0) {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_textView resignFirstResponder];
    [self.view endEditing:YES];
}

#pragma mark - **************** 初始化UICollectionView选择照片
- (void)LQPhotoPicker_initPickerView {
    CGFloat s_width = [UIScreen mainScreen].bounds.size.width;
    CGFloat s_height = [UIScreen mainScreen].bounds.size.height;
    UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((s_width - 50) / 4, (s_width - 50) / 4);
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 10;
    
    self.CollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, s_width, s_height - 120) collectionViewLayout:layout];
    [self.CollectionView registerClass:[JMFeedbackCell class] forCellWithReuseIdentifier:@"JMFeedbackCell"];
    [_scrollView addSubview:self.CollectionView];
    self.CollectionView.delegate = self;
    self.CollectionView.dataSource = self;
    self.CollectionView.backgroundColor = [UIColor whiteColor];
    _CollectionView.scrollEnabled = NO;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JMFeedbackCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"JMFeedbackCell" forIndexPath:indexPath];
    cell.model = _dataSource[indexPath.row];
    cell.DidSelect = ^(JMFeedbackModel * _Nonnull model, BOOL isDele) {
        isDele?[self deletePhoto:model]:[self pickerImage];
    };
    return cell;
}

#pragma mark - 图片cell点击事件
- (void) tapProfileImage:(JMFeedbackModel *)model {
    
}

#pragma mark -- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info {
    UIImage *originImage = info[UIImagePickerControllerOriginalImage];
    NSString *imagePath = [info[@"UIImagePickerControllerImageURL"] absoluteString];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *JMCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cachePath = [JMCachePath stringByAppendingPathComponent:imagePath.lastPathComponent];
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:cachePath];
        NSData *data = [self compressImage:originImage toByte:10240];
        if (!isExist) {
            [data writeToFile:cachePath atomically:YES];
        }
        // <JMFeedbackModel: 0x600001eadef0>
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.dataSource.count < 4) {
                JMFeedbackModel *model = [[JMFeedbackModel alloc] init];
                model.image = [UIImage imageWithData:data];
                model.filePath = cachePath;
                [self.dataSource insertObject:model atIndex:0];
                
                [self rightItemEnable];
                self.iLabel.text = [NSString stringWithFormat:@"请提供相关问题的截图或照片(%ld/3)",self.dataSource.count-1];
                //正方形缩略图 Array
                [self.CollectionView reloadData];
            }
        });
    });
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

// 添加代码，处理选中图像又取消的情况
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)pickerImage {
    if (_dataSource.count > 3) {
        UIAlertController *al = [UIAlertController alertControllerWithTitle:@"提示" message:@"选择图片数量已达上限" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ac = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [al addAction:ac];
        [self presentViewController:al animated:YES completion:NULL];
    }else {
        CGFloat width = self.view.bounds.size.width;
        CGFloat height = self.view.bounds.size.height;
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
        picker.view.frame = CGRectMake(0, 0, width, height - 64);
        picker.delegate = self;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = NO;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark - 删除照片
- (void)deletePhoto:(JMFeedbackModel *)model
{
    NSInteger index = [_dataSource indexOfObject:model];
    [_dataSource removeObjectAtIndex:index];
    [_CollectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    if (_dataSource.count == 1) {[self rightItemEnable];}
}

- (void)cacheImage:(NSString *)imagePath size:(CGSize)size {
    NSString *JMCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cachePath = [JMCachePath stringByAppendingPathComponent:imagePath.lastPathComponent];
    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:cachePath];
    if (!isExist) {
        NSData *data = [self compressImage:[UIImage imageWithContentsOfFile:imagePath] toByte:10240];
        [data writeToFile:cachePath atomically:YES];
    }
}

// 压缩照片质量和大小
- (NSData *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return data;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return data;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return data;
}
//{
//    dirname = "/var/www/html/source/wallpaper_upload/MasterBoard/";
//    fileName = "1577957325004.jpg";
//    status = true;
//}

@end

#pragma mark - **************** JMFeedbackModel
@implementation JMFeedbackModel
@end

#pragma mark - **************** JMFeedbackTextView
@implementation JMFeedbackTextView
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setPlaceholder:@""];
        [self setPlaceholderColor:[UIColor lightGrayColor]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)setPlaceholder:(NSString *)placeholder {
    if (_placeholder != placeholder) {
        _placeholder = placeholder;
        [_placeHolderLabel removeFromSuperview];
        _placeHolderLabel = nil;
        [self setNeedsDisplay];
    }
}

- (void)textChanged:(NSNotification *)notification {
    if ([[self placeholder] length] == 0) {return;}
    if ([[self text] length] == 0) {
        [[self viewWithTag:999] setAlpha:1.0];
    }else{
        [[self viewWithTag:999] setAlpha:0];
    }
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    if ([[self placeholder] length] > 0) {
        if (_placeHolderLabel == nil) {
            _placeHolderLabel = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, self.bounds.size.width - 16, 0)];
            _placeHolderLabel.lineBreakMode = NSLineBreakByWordWrapping;
            _placeHolderLabel.numberOfLines = 0;
            _placeHolderLabel.font = self.font;
            _placeHolderLabel.backgroundColor = [UIColor clearColor];
            _placeHolderLabel.textColor = self.placeholderColor;
            _placeHolderLabel.alpha = 0;
            _placeHolderLabel.tag = 999;
            [self addSubview:_placeHolderLabel];
        }
        _placeHolderLabel.text = self.placeholder;
        [_placeHolderLabel sizeToFit];
        [self sendSubviewToBack:_placeHolderLabel];
    }
    if ([[self text] length] == 0 && [[self placeholder] length] >0) {
        [[self viewWithTag:999] setAlpha:1.0];
    }
}
@end

#pragma mark - **************** JMFeedbackCell
@interface JMFeedbackCell()
@property(nonatomic, weak) UIImageView *bigImage;
@property(nonatomic, weak) UIButton *close;
@end

@implementation JMFeedbackCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIImageView *bigView = [[UIImageView alloc] initWithFrame:CGRectZero];
        bigView.contentMode = UIViewContentModeScaleAspectFill;
        bigView.clipsToBounds = YES;
        [self addSubview:bigView];
        self.bigImage = bigView;
        
        //添加图片cell点击事件
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapProfileImage:)];
        bigView.userInteractionEnabled = YES;
        [bigView  addGestureRecognizer:singleTap];
        
        UIButton *btnAction = [UIButton buttonWithType:(UIButtonTypeSystem)];
        [btnAction addTarget:self action:@selector(deletePhoto:) forControlEvents:(UIControlEventTouchUpInside)];
        [btnAction setImage:[[UIImage imageNamed:@"pick_close"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
        [self addSubview:btnAction];
        self.close = btnAction;
    }
    return self;
}

- (void)setModel:(JMFeedbackModel *)model {
    _model = model;
    _close.hidden = !model.assets;
    _bigImage.image = model.image;
}

- (void)deletePhoto:(UIButton *)sender {
    if (self.DidSelect) { self.DidSelect(_model, YES); }
}

- (void)tapProfileImage:(UITapGestureRecognizer *)gestureRecognizer {
    if (self.DidSelect) { self.DidSelect(_model, NO); }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    _bigImage.frame = CGRectMake(0, 10, width-10, height-10);
    _close.frame = CGRectMake(width-30, 0, 30, 30);
}

@end
